package com.example.presentshopping.ui.fragment

import BaseRecyclerAdapter
import BaseRecyclerHolder
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.graphics.Paint
import android.os.Bundle
import android.view.View
import android.view.ViewTreeObserver.OnGlobalLayoutListener
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.bigkoo.convenientbanner.ConvenientBanner
import com.example.presentshopping.R
import com.example.presentshopping.config.base.BaseMvpFragment
import com.example.presentshopping.config.base.MyApplication
import com.example.presentshopping.config.bean.IamgeViewBean
import com.example.presentshopping.config.bean.SupplierListBean
import com.example.presentshopping.mvp.presenter.PublicPresenter
import com.example.presentshopping.net.http.HttpRequest
import com.example.presentshopping.net.http.HttpURL
import com.example.presentshopping.net.observer.TaskCallback
import com.example.presentshopping.ui.activity.*
import com.example.presentshopping.ui.custom.NoDoubleClickListener
import com.example.presentshopping.utils.ToastUtil
import com.example.presentshopping.utils.glide.GlideUtil
import com.example.presentshopping.utils.tool.GsonUtils
import com.example.presentshopping.utils.tool.IntentJumpUtils
import com.example.presentshopping.utils.tool.LogUtils
import com.yanzhenjie.recyclerview.SwipeRecyclerView
import kotlinx.android.synthetic.main.fragment_gather.*


class GatherFragment : BaseMvpFragment() {

    var baseRecyclerAdapter: BaseRecyclerAdapter<SupplierListBean.DataBean.ListBean>? = null
    var headerView: View? = null
    var cb_banner: ConvenientBanner<IamgeViewBean>? = null
    var supplierListBean: SupplierListBean? = null
    var refreshlayout: SwipeRefreshLayout? = null

    var ly_TitleView: LinearLayout? = null
    var iv_pintun: ImageView? = null

    var page = 1
    var type = 1

    // 获取控件高度
    private var mHeight = 0

    lateinit var recycler_view: SwipeRecyclerView
    private var queryInfoPresenter: PublicPresenter? = null
    override val layoutId: Int
        get() = R.layout.fragment_gather

    @SuppressLint("NewApi")
    override fun initView(view: View?, savedInstanceState: Bundle?) {
        queryInfoPresenter = PublicPresenter(context, true, "加载中")
        queryInfoPresenter?.attachView(this)
        RgetGoodsList(1)
        refreshlayout = view?.findViewById(R.id.refresh_layout)
        recycler_view = view?.findViewById(R.id.recycler_view)!!

        // 客户数据View
        recycler_view.layoutManager = GridLayoutManager(context, 2)
        recycler_view.useDefaultLoadMore()
        headerView =
            layoutInflater.inflate(R.layout.fragment_client_head_view, recycler_view, false)
        recycler_view.addHeaderView(headerView)

        cb_banner = headerView?.findViewById<ConvenientBanner<IamgeViewBean>>(R.id.cbanner_img)
        ly_TitleView = headerView?.findViewById(R.id.ly_TitleView)
        setBaseIamgview(headerView)
        // 使用默认的加载更多的View。
        // 添加分隔线
        //recycler_view.addItemDecoration(dividerList);

        // 使用默认的加载更多的View。
        recycler_view.useDefaultLoadMore()
        recycler_view.loadMoreFinish(false, true)
        //上拉加载

        refreshlayout?.setOnRefreshListener {
            page = 1
            RgetGoodsList(page)
        }
        recycler_view?.setLoadMoreListener {
            page++
            RgetGoodsList(page)
        }

        // 获取控件高度
        val vto = ly_TitleView!!.viewTreeObserver
        vto.addOnGlobalLayoutListener(object : OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                //ly_TitleView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                ly_TitleView!!.viewTreeObserver.removeOnGlobalLayoutListener(this)
                ly_TitleView!!.width
                mHeight = ly_TitleView!!.height
            }
        })


        recycler_view?.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->

            //int mHeight = ly_TitleView.getHeight();//获取状态栏高度
            //滑动距离
            var sy: Int = getScollYDistance()
            if (mHeight > 0) {
                if (sy <= mHeight) { //滑动过程中 并且在mHeight之内
                    ly_TitleView3?.visibility = View.GONE
                } else { //超过mHeight
                    ly_TitleView3?.visibility = View.GONE
                }
            } else {
                ly_TitleView3?.visibility = View.GONE
            }

        }

        getlabem()
        setBaseAdapter()
    }


    //商品列表
    fun setBaseAdapter() {
        baseRecyclerAdapter = object : BaseRecyclerAdapter<SupplierListBean.DataBean.ListBean>(
            context,
            null,
            R.layout.item_more_refuel
        ) {
            @SuppressLint("SetTextI18n")
            override fun convert(
                holder: BaseRecyclerHolder?,
                data: SupplierListBean.DataBean.ListBean,
                position: Int,
                isScrolling: Boolean,
                selectedPosition: Int
            ) {
                val ivthumb = holder?.getView<ImageView>(R.id.iv_image)
                val tvname = holder?.getView<TextView>(R.id.tv_name)
                val discountinfo = holder?.getView<TextView>(R.id.discount_info)
                val tvdistance = holder?.getView<TextView>(R.id.tv_distance)
                val mLlGoods = holder?.getView<LinearLayout>(R.id.mLlGoods)
                tvname?.text = data.title
                discountinfo?.text = "¥:" + data.marketprice
                tvdistance?.text = "¥:" + data.productprice
                tvdistance?.paint?.flags = Paint.STRIKE_THRU_TEXT_FLAG;
                GlideUtil.load(context, data.thumb, ivthumb)
                mLlGoods?.setOnClickListener {
                    val Init = Intent(context, DetailsActivity().javaClass)
                    Init.putExtra("msid", data.id.toString())
                    Init.putExtra("Activity", "GatherFragment")
                    context?.startActivity(Init)
                }
            }
        }
        recycler_view.adapter = baseRecyclerAdapter


    }

    //
    fun setBaseIamgview(view: View?) {
        view?.findViewById<ImageView>(R.id.iv_pintun)?.setOnClickListener { context?.startActivity(Intent(context, SpellgroupActivity().javaClass)) }
        view?.findViewById<LinearLayout>(R.id.sec_category0)?.setOnClickListener { startActivity(Intent(context, ExperienceActivity().javaClass)) }
        view?.findViewById<LinearLayout>(R.id.sec_category1)?.setOnClickListener(OnCancelListener)
        view?.findViewById<LinearLayout>(R.id.sec_category2)?.setOnClickListener(OnCancelListener)
        view?.findViewById<LinearLayout>(R.id.sec_category3)?.setOnClickListener(OnCancelListener)
        view?.findViewById<LinearLayout>(R.id.sec_category4)?.setOnClickListener {  context?.startActivity(Intent(context, SpellgroupActivity().javaClass)) }
        view?.findViewById<LinearLayout>(R.id.sec_category5)?.setOnClickListener(OnCancelListener)
        view?.findViewById<LinearLayout>(R.id.sec_category6)?.setOnClickListener(OnCancelListener)
        view?.findViewById<LinearLayout>(R.id.sec_category7)?.setOnClickListener(OnCancelListener)
        view?.findViewById<ImageView>(R.id.sec_category8)?.setOnClickListener(OnCancelListener)
        view?.findViewById<ImageView>(R.id.sec_category9)?.setOnClickListener(OnCancelListener)


//        myhotCrunchies?.setOnClickListener {
//            //   showToast("功能暂未开放")
//
//            type = 1
//            page = 1
//            RgetGoodsList(page)
//            myhotCrunchies.setTextColor(Color.parseColor("#F11801"))
//            mynewstart?.setTextColor(Color.parseColor("#ff191919"))
//            myrecommendation?.setTextColor(Color.parseColor("#ff191919"))
//
//
//        }
//
//        mynewstart?.setOnClickListener {
//            //    showToast("功能暂未开放")
//
//            type = 2
//            page = 1
//            RgetGoodsList(page)
//            myhotCrunchies?.setTextColor(Color.parseColor("#ff191919"))
//            mynewstart.setTextColor(Color.parseColor("#F11801"))
//            myrecommendation?.setTextColor(Color.parseColor("#ff191919"))
//
//        }
//
//        myrecommendation?.setOnClickListener {
//
//            page = 1
//            type = 3
//            RgetGoodsList(page)
//            //  showToast("功能暂未开放")
//            myhotCrunchies?.setTextColor(Color.parseColor("#ff191919"))
//            mynewstart?.setTextColor(Color.parseColor("#ff191919"))
//            myrecommendation.setTextColor(Color.parseColor("#F11801"))
//
//        }

    }

    val OnCancelListener = object : NoDoubleClickListener() {
        override fun onNoDoubleClick(v: View?) {
            if (IntentJumpUtils.isLogin()) {
            when (v?.id) {
                R.id.sec_category1 -> {
                    val iniet = Intent(context, LuckydrawActivity().javaClass)
                    iniet.putExtra("Activity", "Turntable")
                    startActivity(iniet)
                }
                R.id.sec_category2 -> {
                    val inito = Intent(context, SignInActivity().javaClass)
                    startActivity(inito)
                }
                R.id.sec_category3 -> {
                    val iniet = Intent(context, InformationActivity().javaClass)
                    iniet.putExtra("Activity", "message")
                    startActivity(iniet)
                }

                R.id.sec_category5 -> {
                    startActivity(Intent(context, ComesQCasActivity().javaClass))
                }
                R.id.sec_category6 -> showToast("功能暂未开放")
                R.id.sec_category7 -> {
                    //排行榜
//            startActivity(
//                Intent(context, SeniorityActivity().javaClass)
//            )
                    showToast("功能暂未开放")
                }
                R.id.sec_category8 -> showToast("功能暂未开放")
                R.id.sec_category9 -> showToast("功能暂未开放")

            }
            } else {
                // 登录
           //    queryInfoPresenter?.showAlertDialog(MyApplication.getContext(), "")
                IntentJumpUtils.goToLogin(context, "")
            }


        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        queryInfoPresenter?.detachView()
    }

    override fun onSuccess(data: String?) {
    }

    override fun onFailure(e: Throwable?, code: Int, msg: String?, isNetWorkError: Boolean) {

    }

    //轮播图
    fun getlabem() {
        queryInfoPresenter?.netWorkRequestPost(
            HttpURL.Req_ggetCarousel,
            HttpRequest.getGoodsList(1, 1, 10),
            object : TaskCallback {
                override fun onSuccess(data: String?) {
                    LogUtils.p("onSuccess-----", data)
                    val beanbr = GsonUtils.getGson().fromJson(data, IamgeViewBean().javaClass)
                    if (beanbr.data?.list!!.isEmpty()) {
                    } else {
                        cb_banner?.setPageIndicator(
                            intArrayOf(
                                R.mipmap.xiang_huise,
                                R.mipmap.xing_bai
                            )
                        )
                        cb_banner?.setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                        IntentJumpUtils.setPase(cb_banner, beanbr?.data?.list as List<Any>?)
                        cb_banner?.startTurning(3000)
                    }
                }

                override fun onFailure(
                    e: Throwable?,
                    code: Int,
                    msg: String?,
                    isNetWorkError: Boolean
                ) {


                }

            })
    }

    //获取商品列表
    fun RgetGoodsList(inv: Int) {
        queryInfoPresenter?.netWorkRequestPost(
            HttpURL.Req_getGoodsList,
            HttpRequest.getGoodsList(type, inv, 10),
            object : TaskCallback {
                override fun onSuccess(data: String?) {
                    refreshlayout?.isRefreshing = false

                    supplierListBean =
                        GsonUtils.getGson().fromJson(data, SupplierListBean().javaClass)
                    if (page == 1) {
                        baseRecyclerAdapter?.clear()
                    }
                    if (supplierListBean?.data?.list?.size!! > 0) {
                        recycler_view.loadMoreFinish(false, true)
                        baseRecyclerAdapter?.setData(supplierListBean?.data?.list)
                    } else {
                        recycler_view.loadMoreFinish(true, false)
                    }

                }

                override fun onFailure(
                    e: Throwable?,
                    code: Int,
                    msg: String?,
                    isNetWorkError: Boolean
                ) {
                    ToastUtil.showMsg(msg)
                }
            })
    }

    // 如果LayoutManager用的是LinearLayoutManager，强烈推荐下面的方法获取滑动距离：
    fun getScollYDistance(): Int {
        try {
            val layoutManager = recycler_view.layoutManager as LinearLayoutManager?
            if (layoutManager != null) {
                val position = layoutManager.findFirstVisibleItemPosition()
                val firstVisiableChildView = layoutManager.findViewByPosition(position)
                if (firstVisiableChildView != null) {
                    val itemHeight = firstVisiableChildView.height
                    return position * itemHeight - firstVisiableChildView.top
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return 0
    }

    override fun showToast(msg: String?) {
        ToastUtil.showMsg(msg)
    }

}